<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <!-- <a-col :span="24">
            <a-form-model-item label="编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入编码"  ></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="申请人名称/实际权属主体" :labelCol="{
          xs: { span: 24 },
          sm: { span: 8 },
        }" :wrapperCol="{
          xs: { span: 24 },
          sm: { span: 13 },
        }" prop="name">
              <a-input v-model="model.name" placeholder="请输入申请人名称/实际权属主体"  ></a-input>
             
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="删除标识，1为删除" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isDel">
              <a-input v-model="model.isDel" placeholder="请输入删除标识，1为删除"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="附加字段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="addFields">
              <a-input v-model="model.addFields" placeholder="请输入附加字段"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="创建人账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createUserId">
              <a-input v-model="model.createUserId" placeholder="请输入创建人账号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="修改时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastTime">
              <j-date placeholder="请选择修改时间" v-model="model.lastTime"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="修改人账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastUserId">
              <a-input v-model="model.lastUserId" placeholder="请输入修改人账号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createUser">
              <a-input v-model="model.createUser" placeholder="请输入创建人"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="修改人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastUser">
              <a-input v-model="model.lastUser" placeholder="请输入修改人"  ></a-input>
            </a-form-model-item>
          </a-col> -->
           <a-col :span="24">
            <a-form-model-item label="数据权限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="authority">
              <a-input type="hidden" v-model="model.authority" placeholder="请输入数据权限"  ></a-input>
               <a-select
              
                mode="multiple"
                label-in-value
                :value="searchUservalue"               
                placeholder="Select users"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="fetchUser"
                @change="handlesearchUserChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in searchUserData" :key="d.value">
                  {{ d.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction,getActionAsync } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
import debounce from 'lodash/debounce';

  export default {
    name: 'BrandApplicantMainForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      this.lastFetchId = 0;
      this.fetchUser = debounce(this.fetchUser, 800);
      return {
         searchUserData: [],
      searchUservalue: [],
      fetching: false,
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          //  code: [
          //     { required: true, message: '请输入编码!'},
          //  ],
           name: [
              { required: true, message: '申请人名称/实际权属主体!'},
           ],
          //  isDel: [
          //     { required: true, message: '请输入删除标识，1为删除!'},
          //  ],
        },
        url: {
          add: "/knowledge/brandApplicantMain/add",
          edit: "/knowledge/brandApplicantMain/edit",
          queryById: "/knowledge/brandApplicantMain/queryById",
          selUserList:"/upms/user/selUserList",
          userList:"/upms/user/list",
          
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
     
    },

    methods: {

     async handleDefaultAuthority (){
        let searchUservalue =[]
        let authority = this.model.authority;
    
        
        if(!!authority){
         let authorityArr = authority.split(",");
         for (let index = 0; index < authorityArr.length; index++) {
           const element = authorityArr[index];
           let res = await getActionAsync(this.url.userList,{username:element});

           if(res.success){
             let userInfo = res.result.records[0]
             if(!!userInfo){
              searchUservalue.push({key:userInfo.username,label:`${userInfo.username} ${userInfo.realname}`})
             }
            
           }
         

         }
          this.searchUservalue = searchUservalue;
        }
      },
   
      fetchUser(value) {
      let that = this
      console.log('fetching user', value);
      this.lastFetchId += 1;
      const fetchId = this.lastFetchId;
      this.searchUserData = [];
      this.fetching = true;
      getAction(this.url.selUserList,{keyword:value}).then(res => {
          if (fetchId !== this.lastFetchId) {
            // for fetch callback order
            return;
          }
          if(res.success){
              const data = res.result.records.map(user => ({
            text: `${user.username} ${user.realname}`,
            value: user.username,
          }));
           that.searchUserData = data;
          
          that.fetching = false;
         
          }
          
        });
   
    },
    handlesearchUserChange(value) {
      
      Object.assign(this, {
        searchUservalue:value,
        searchUserData: [],
        fetching: false,
      });
      let searchUservalue = this.searchUservalue
      let authorityArr = []
      for (let index = 0; index < searchUservalue.length; index++) {
        const element = searchUservalue[index];
        authorityArr.push(element.key)
        
      }
      this.model.authority = authorityArr.join(",")
      
    },
    deselect(value){
       let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
           
          },
          onCancel:function () {
           that.searchUservalue.push(value)
          }
        });
    },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.handleDefaultAuthority();
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>